package com.xiubai.appforpda.activitys;

import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xiubai.appforpda.App;
import com.xiubai.appforpda.R;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.WebAssetEntity;
import com.xiubai.appforpda.entity.WebLocationEntity;
import com.xiubai.appforpda.entity.WebMainPamInventEntity;
import com.xiubai.appforpda.entity.WebNCGetUseEntity;
import com.xiubai.appforpda.entity.WebOrgStructureEntity;
import com.xiubai.appforpda.entity.WebPamInventEntity;
import com.xiubai.appforpda.entity.WebPamStatusEntity;
import com.xiubai.appforpda.entity.WebPersonEntity;
import com.xiubai.appforpda.event.CloseEvent;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.SharedPreferenceTool;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.Utils;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.utils.ActivityStackManager;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.ErrorMsgException;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;

import org.greenrobot.eventbus.EventBus;
import org.ksoap2.serialization.SoapObject;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;

/**
 * @author: r3562939
 * @version: V1.0
 * @project: AppForPda
 * @description: description
 * @date: 2018/11/13
 * @time: 13:09
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_ip;
    private EditText et_port;
    private View btn_confirm;
    private String ip;
    private String port;
    private CustomDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
        initData();
    }

    private void initData() {
        String ip = SharedPreferenceTool.getInstance().getString(AppConstants.IP);
        String port = SharedPreferenceTool.getInstance().getString(AppConstants.PORT);
        if (!TextUtils.isEmpty(ip)) {
            et_ip.setText(ip);
            et_ip.setSelection(ip.length());
        }
        if (!TextUtils.isEmpty(port)) {
            et_port.setText(port);
            et_port.setSelection(port.length());
        }
    }

    private void initView() {
        et_ip = (EditText) findViewById(R.id.et_ip);
        et_port = (EditText) findViewById(R.id.et_port);
        et_ip.setRawInputType(Configuration.KEYBOARD_QWERTY);
        et_port.setRawInputType(Configuration.KEYBOARD_QWERTY);
        btn_confirm = findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                ip = et_ip.getText().toString();
                port = et_port.getText().toString();
                if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
                    Toast.makeText(this, "IP或端口号不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!checkIp(ip)) {
                    Toast.makeText(this, "IP地址格式不正确!", Toast.LENGTH_SHORT).show();
                    return;
                }

                doLogin();
                break;
        }
    }

    private boolean checkIp(String ip) {
        boolean is = true;
        try {
            InetAddress.getByName(ip);
        } catch (Exception e) {
            is = false;
        }
        return is;
    }

    private void doLogin() {
        AppConstants.IP_ADDRESS = ip;
        AppConstants.PORT_ADDRESS = port;

        SharedPreferenceTool.getInstance().saveString(AppConstants.IP_ADDRESS, ip);
        SharedPreferenceTool.getInstance().saveString(AppConstants.PORT_ADDRESS, port);

        loadBaseData();

//        ActivityStackManager.getInstance().finishActivity(SettingActivity.class);
    }

    private void loadBaseData(){
        AsyncTask<Integer,Integer,Integer> asyncTask = new AsyncTask<Integer, Integer, Integer>() {
            String msg = "";
            String status = "";
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog("抓取NC基础数据中...");
            }

            @Override
            protected Integer doInBackground(Integer... integers) {

                try{
                    callWS(AppConstants.GET_PERSON);
                    //callWS(AppConstants.GET_ASSET_DATA);
                    callWS(AppConstants.GET_ORG_DEPT);
                    callWS(AppConstants.GET_PAM_LOCATION);
                    callWS(AppConstants.GET_PAM_STATUS);
                }catch (ErrorMsgException e){
                    msg = e.msg;
                    status = e.status;
                    return 1;
                }catch (Exception e){
                    return 2;
                }

                return 0;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                super.onPostExecute(integer);
                dialogDismiss(progressDialog);
                if(integer == 0){
                    enterHome();
                }else if(integer == 1){
                    SharedPreferenceTool.getInstance().remove(AppConstants.IP);
                    SharedPreferenceTool.getInstance().remove(AppConstants.PORT);
                    Toast.makeText(SettingActivity.this, "同步失败" + status + "原因" + msg, Toast.LENGTH_SHORT).show();
                }else if(integer == 2){
                    SharedPreferenceTool.getInstance().remove(AppConstants.IP);
                    SharedPreferenceTool.getInstance().remove(AppConstants.PORT);
                    Toast.makeText(SettingActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    private void callWS(final String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            switch (url) {
                                case AppConstants.GET_PERSON:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());  //组织人员
                                    break;
                                case AppConstants.GET_ASSET_DATA:
                                    WebAssetEntity webAssetEntity = JsonParser.deserializeByJson(json, WebAssetEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamAssetBean.class);
                                    DatabaseUtils.getHelper().saveAll(webAssetEntity.getPam_asset()); // 设备
                                    break;
                                case AppConstants.GET_ORG_DEPT:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept()); //部门
                                    break;
                                case AppConstants.GET_PAM_LOCATION:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc()); //位置
                                    break;
                                case AppConstants.GET_PAM_STATUS:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                    DatabaseUtils.getHelper().saveAll(pamStatusBean.getPam_sta()); //状态
                                    break;
                            }
                        } else {
                            throw new ErrorMsgException("",assetBean.msg,assetBean.status);
                        }
                    } else {
                        throw new ErrorMsgException("","返回JSON数据格式异常","");
                    }
                }else {
                    if (!Utils.checkNetworkIsAvailable()) {
                        throw new ErrorMsgException("","请检查网络连接情况","");
                    }
                    throw new ErrorMsgException("","IP设置或PORT设置有误,请检查","");
                }
            }
        });
    }

    private void showProgressDialog(String message) {
        progressDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        progressDialog.setView(LayoutInflater.from(this).inflate(R.layout.promt_data_input_layout, null));
        TextView tv_input = (TextView) progressDialog.findId(R.id.tv_input_promt);
        if (tv_input != null) {
            tv_input.setText(message);
        }
        progressDialog.setCanceledOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        dialogMatchWindow(progressDialog);
    }

    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

    private void enterHome() {
        SharedPreferenceTool.getInstance().saveString(AppConstants.IP, ip);
        SharedPreferenceTool.getInstance().saveString(AppConstants.PORT, port);
        App.ALREADY_SYNC = true;
        finish();
    }
}
